package com.gold.config.client;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.cloud.context.refresh.ContextRefresher;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.env.Environment;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;
import java.io.Closeable;
import java.util.concurrent.atomic.AtomicBoolean;

public class ConfigClientWatch
        implements Closeable, EnvironmentAware
{
    private static Log log = LogFactory.getLog(ConfigServicePropertySourceLocator.class);
    private final AtomicBoolean running = new AtomicBoolean(false);
    private final ContextRefresher refresher;
    private Environment environment;

    public ConfigClientWatch(ContextRefresher refresher)
    {
        this.refresher = refresher;
    }

    public void setEnvironment(Environment environment)
    {
        this.environment = environment;
    }

    @PostConstruct
    public void start()
    {
        this.running.compareAndSet(false, true);
    }

    @Scheduled(initialDelayString="${spring.cloud.config.watch.initialDelay:180000}", fixedDelayString="${spring.cloud.config.watch.delay:500}")
    public void watchConfigServer()
    {
        if (this.running.get())
        {
            String newState = this.environment.getProperty("config.client.state");
            String oldState = ConfigClientStateHolder.getState();
            if (stateChanged(oldState, newState))
            {
                ConfigClientStateHolder.setState(newState);
                this.refresher.refresh();
            }
        }
    }

    boolean stateChanged(String oldState, String newState)
    {
        return ((!StringUtils.hasText(oldState)) && (StringUtils.hasText(newState))) || ((StringUtils.hasText(oldState)) && (!oldState.equals(newState)));
    }

    public void close()
    {
        this.running.compareAndSet(true, false);
    }
}

